package com.fast.fastenjoy.base.dao.sqltemplate;

import java.util.HashMap;
import java.util.Map;

import com.fast.fastenjoy.base.dao.sqltemplate.domain.SqlMap;
import com.fast.fastenjoy.base.dao.sqltemplate.domain.SqlOpType;
import com.fast.fastenjoy.base.dao.sqltemplate.exception.SQLTemplateException;
import com.fast.fastenjoy.base.dao.sqltemplate.impl.XMLSQLTemplateProcessor;
import com.fast.fastenjoy.freemarker.utils.FreemarkerTemplateEngine;

/**
 * SQL 模板
 * @author chenliaohua
 *
 */
public class SQLTemplate{

	private static final Map<String, SqlMap> CACHE = new HashMap<String, SqlMap>();
	
	private static SQLTemplateProcessor sqlTemplateProcessor = new XMLSQLTemplateProcessor();
	
	public static void init(){
		CACHE.putAll(sqlTemplateProcessor.getSQLMap());
	}
	
	private static SqlMap getSqlMap(String sqlId){
		return CACHE.get(sqlId);
	}
	
	public static SqlMap getSqlMap(String sqlId, SqlOpType aqlOpType) throws SQLTemplateException{
		
		SqlMap sqlMap = getSqlMap(sqlId);
		
		if(sqlMap == null){
			throw new SQLTemplateException("not find sqlId[" + sqlId + "]");
		}
		
		if(sqlMap.getSqlOpType() != aqlOpType){
			throw new SQLTemplateException("sqlId[" + sqlId + "][" + sqlMap.getSqlOpType() + "]  not is " + aqlOpType + "");
		}
		
		return sqlMap;
	}
	
	public static String builderSqL(SqlMap sqlMap, Map<String, Object> paramMap){
		
		String sqlContext = sqlMap.getSqlContext();
		
		try {
			sqlContext = FreemarkerTemplateEngine.renderFtlStr(sqlContext, paramMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return sqlContext;
	}
	
}
